//
//  CDRecommendController.swift
//  CDLiftWithDisplay
//
//  Created by SteveLi on 2017/9/18.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit

private let reuseIdentifier = "recommendCell"

class CDRecommendController: UICollectionViewController {
    //懒加载从模型获取数据
    lazy var dataArray:[CDRecommendModel] = CDRecommendModel.recommendInfos()
    //记录当前cell下标的变量
    var currentCellIndex: Int = 0
    //执行动画循环的定时器
    var animaTimer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    //开启定时器
    func startTimer(){
        if animaTimer == nil {
            animaTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(cellAnimation), userInfo: nil, repeats: true)
        }
    }
    //停止定时器
    func stopTimer() {
        if animaTimer == nil {
            return
        }
        animaTimer?.invalidate()
        animaTimer = nil
    }
    //在生命周期方法中
    //视图显示完成
    override func viewDidAppear(_ animated: Bool) {
        startTimer()
    }
    //视图即将消失
    override func viewWillDisappear(_ animated: Bool) {
        stopTimer()
    }
    
    
    //cell动画方法
    func cellAnimation(){
        //判断当前下标是否越界
        if currentCellIndex > (dataArray.count - 1) {
            currentCellIndex = 0
        }
        //获取要动画的cell
        let indexP = IndexPath(item: currentCellIndex, section: 0)
        guard  let cell = collectionView?.cellForItem(at: indexP) else {
            return
        }
        //让cell视图翻转
        UIView.transition(with: cell, duration: 1, options: .transitionFlipFromRight, animations: nil) { [weak self](_) in
            //修改cell下标
            self?.currentCellIndex += 1
        }
        
    }
    
  
   }

extension CDRecommendController{
    //设置返回多少个格子视图
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    //你的每一个格子要显示什么内容
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CDRecommendCell
            //获取对应模型并赋值
            cell.recommendModel = dataArray[indexPath.row]
            return cell
    }
    
    //cell点击后的事件回调方法
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //从sb中获取视图
        let detailVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CDRecDetail") as! CDRecDetailController
        detailVc.recommendModel = dataArray[indexPath.item]
        //设置影藏底部标签栏
        detailVc.hidesBottomBarWhenPushed = true
        //导航推送
        navigationController?.pushViewController(detailVc, animated: true)
        
        
    }

}










